package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.analyse.JSoupUtils;
import com.kdtech.crawler.CrawlHTML;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.StringUtils;
import com.kdtech.utils.HtmlCleaner;

/**
 * 香港文汇网  网站解析
 * @author Chase
 *
 */
public class WenweipoNewsAnalyse implements AnalyseNews {

	private static final String[] regex={
		"http://.*.wenweipo.com/[0-9]*/[0-9]*/[0-9]*/IN[0-9]*.htm",
		"http://.*.wenweipo.com/.*/[0-9]*/[0-9]*.html",
	};


	
	public boolean isDetailPage(String url) {
		for (int i=0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return false;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta news=new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}
		String url=urlMeta.getUrl();
		/*
		 * 网站源码
		 */
		String htmltxt=urlMeta.getHtml();

		if(!isDetailPage(url)){
		}


		String title=null;
		String content=null;
		String author=null;
		Long date=null;
		Document doc=Jsoup.parse(htmltxt);

		/*
		 * 标题
		 */
		title=doc.select("title").text();
		if (title.contains("--")){
			title=StringUtils.substringBefore(title, "--");
		}else if (title.contains("-")){
			title=StringUtils.substringBefore(title, "-");
		}


		/*
		 * 内容
		 */
		content=HtmlCleaner.getContentHtml(url,doc.select("td.zztext"));
		if (StringUtils.isBlank(content)) {
			content=HtmlCleaner.getContentHtml(url,doc.select("p.title_p,p.ct_p"));
		}
		if (StringUtils.isBlank(content)) {
			content=HtmlCleaner.getContentHtml(url,doc.select("div#content"));
			if (StringUtils.isBlank(content)) {
				content=HtmlCleaner.getContentHtml(url,doc.select("div#page3"));
			}
		}

		/*
		 * 作者
		 */
		author =JSoupUtils.matchAuthor(doc, "来源：");

		date=DateUtils.matchDate(doc.select("td[height=15]").text());
		if (date == null) {
			date=DateUtils.matchDate(doc.select("li").text());
			if (date == null) {
				date=DateUtils.matchDate(doc.select("div#page2").text());
			}
		}
		if (date == null) {
			date=DateUtils.matchDate(url);
		}

		news.setUrl(url);

		news.setTitle(title);
		news.setContent(content);
		news.setAuthor(author);
		news.setDate(date);
		return news;
	}

	public static void main(String[] args) {
		WenweipoNewsAnalyse analyse=new WenweipoNewsAnalyse();
		String url="http://news.wenweipo.com/2014/07/09/IN1407090019.htm";
		url=UrlArgumentTop.FromatUrl(url);
		System.err.println(url);
		UrlMeta meta=CrawlHTML.responseToURL(url);
		System.out.println(analyse.parserHtml(meta));
	}

	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}


	
	public boolean isNeedUpdate(){
		return false;
	}
}
